package com.rxz.service.impl;

import com.rxz.entity.Message;
import com.rxz.entity.Result;
import com.rxz.utils.ResultUtil;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class MqServiceImpl {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    private int MSG_INDEX = 0;

    public Result sendMQ(String message){
        int index = MSG_INDEX;
        String messageKey = "rxz:message:" + System.currentTimeMillis();
        Long push = redisTemplate.opsForList().rightPush(messageKey,message);
        MSG_INDEX++;
        redisTemplate.opsForValue().set("key",messageKey,15L,TimeUnit.SECONDS);
        if(push < 0){
            return ResultUtil.error(401,"发送失败！");
        }
        Message msgData = new Message();
        msgData.setIndex(index);
        msgData.setMessageKey(messageKey);
        return ResultUtil.success(msgData);
    }

    public Result getMQ(String messageKey,int index){
        String message = redisTemplate.opsForList().index(messageKey,index);
        String key = redisTemplate.opsForValue().get("key");
        if (message == null){
            return ResultUtil.error(401,"收到消息为空！");
        }
        if (key == null){
            return ResultUtil.error(401,"消息过期啦！");
        }
        return ResultUtil.success(message);
    }
}
